package com.zhu.work;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;

import java.io.*;

public class CacheBuilder {

    public static LoadingCache<String, YmsFileBuffer> getResourcesCache(){
        LoadingCache<String, YmsFileBuffer> cache = Caffeine.newBuilder()
                //基于数量的配置
                .maximumSize(500)
                .build(key->createYmsFileCache(key));
        return cache;
    }

    /**
     * key为file路径
     * @param key
     * @return
     */
    private static YmsFileBuffer createYmsFileCache(String key) throws IOException {
        try(InputStream is = new FileInputStream(key);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(os);){
            byte[] buffer = new byte[1024];
            int n = -1;
            while ((n = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, n);
            }
            bos.flush();
            YmsFileBuffer ymsfile = new YmsFileBuffer();
            ymsfile.setContext(os.toByteArray());
            return ymsfile;
        }
    }
}
